package com.example.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.controller.util.Code;
import com.example.controller.util.Data;
import com.example.controller.util.SaltMD5Util;
import com.example.controller.util.UserHolder;
import com.example.domain.Admin;
import com.example.domain.Community;
import com.example.domain.PhoneDto;
import com.example.domain.User;
import com.example.mapper.AdminMapper;
import com.example.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.controller.util.RedisConstants.LOGIN_USER_KEY;
import static com.example.controller.util.RedisConstants.LOGIN_USER_TTL;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public IPage<Admin> getPageAdmin(Integer page, Integer size) {
        IPage<Admin> pageInfo = new Page<>(page,size);
        adminMapper.selectPage(pageInfo,null);
        return pageInfo;
    }

//    注册管理员
    @Override
    public boolean saveAdmin(Admin admin) {
        String password=admin.getPassword();
        String saltPassword= SaltMD5Util.generateSaltPassword(password);
        admin.setPassword(saltPassword);
        int insert = adminMapper.insert(admin);
        Boolean a = insert == 1 ? true : false;
        return a;
    }

//    新增查重，添加的代码
    @Override
    public Admin getAdmin(String name) {
        LambdaQueryWrapper<Admin> lwq = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Admin> eq = lwq.eq(Admin::getName, name);
        Admin admin = adminMapper.selectOne(eq);
        return admin;
    }


    //    登录管理员
    @Override
    public Data login(Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getName,admin.getName());
        Admin loginAdmin = adminMapper.selectOne(queryWrapper);
        boolean result = SaltMD5Util.verifySaltPassword(admin.getPassword(), loginAdmin.getPassword());
        if (result==true){
            // 7.1.生成Token
            String token = UUID.randomUUID().toString(true);
            System.out.println("token值为"+token);
            String tokenKey = LOGIN_USER_KEY + token;
//            PhoneDto dto = BeanUtil.copyProperties(loginAdmin, PhoneDto.class);
//            dto.setPhone("");//设置为字符串，否则报空指针错误
//            dto.setCode("");
//            Map<String, Object> userMap = BeanUtil.beanToMap(dto, new HashMap<>(),
//                    CopyOptions.create()
//                            .setIgnoreNullValue(true)
//                            .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
//            stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
//            // 7.4.设置有效期30分钟,但是如果用户在一直访问则必须刷新有效期（用拦截器实现）
//            stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
            return new Data(200,loginAdmin,tokenKey,"登录成功");
        }
        return new Data(201,"登录失败");
    }

    @Override
    public boolean agency() {
        PhoneDto loginAdmin = UserHolder.getUser();
        if (loginAdmin.getAuthority().equals("managerial")){
            return true;
        }
        return false;
    }
}
